package com.cdp.zwy.zwy_manager_back_v1.service;

import cn.hutool.core.util.StrUtil;
import com.cdp.zwy.zwy_manager_back_v1.common.ErrorCode;
import com.cdp.zwy.zwy_manager_back_v1.common.ServiceException;
import com.cdp.zwy.zwy_manager_back_v1.entity.Account;
import com.cdp.zwy.zwy_manager_back_v1.entity.Article;
import com.cdp.zwy.zwy_manager_back_v1.mapper.ArticleLikeMapper;
import com.cdp.zwy.zwy_manager_back_v1.mapper.ArticleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zwy
 * @version 1.0
 * @description: ArticleService
 * @date 2025/4/26 14:22
 */
@Service
public class ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ArticleLikeMapper articleLikeMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final String ARTICLE_LIKES_KEY_PREFIX = "article:likes:";
    private static final String EMPTY_CACHE_PLACEHOLDER = "__EMPTY_SET__"; // 定义空缓存占位符

    public int add(Article article) {
        if(StrUtil.isBlank(article.getTitle())){
            article.setTitle("默认标题");
        }
        if(StrUtil.isBlank(article.getImg())){
            article.setImg("http://localhost:9999/files/download/1745413046623_5.png");
        }
        int row =  articleMapper.insert(article);
        if(row!=1){
            throw new ServiceException(ErrorCode.EMPLOYEE_ADD_ERROR);
        }
        return row;
    }
    public int deleteById(Integer id) {
        Article article = articleMapper.selectById(id);
        if (article == null){
            throw new ServiceException(ErrorCode.EMPLOYEE_NOT_FOUND);
        }
        int row =  articleMapper.deleteById(id);
        if(row!=1){
            throw new ServiceException(ErrorCode.EMPLOYEE_DELETE_ERROR);
        }
        return row;
    }
    public int modify(Article article) {
        Article article1 = articleMapper.selectById(article.getId());
        if (article1 == null){
            throw new ServiceException(ErrorCode.EMPLOYEE_NOT_FOUND);
        }
        int row =  articleMapper.update(article);
        if(row!=1){
            throw new ServiceException(ErrorCode.EMPLOYEE_MODIFY_ERROR);
        }
        return row;
    }
    public Article findById(Integer id) {
        Article article = articleMapper.selectById(id);
        if(article == null){
            throw new ServiceException(ErrorCode.EMPLOYEE_NOT_FOUND);
        }
        return article;
    }
    public List<Article> findAll() {
        List<Article> articles = articleMapper.selectAll();
        if(articles.size() == 0){
            throw new ServiceException(ErrorCode.NOT_DATA);
        }
        return articles;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<Article> selectPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Article> list = articleMapper.selectAll();

        return PageInfo.of(list);
    }

    public PageInfo<Article> findByTitle(Integer pageNum, Integer pageSize, String title) {
        PageHelper.startPage(pageNum,pageSize);
        List<Article> list = articleMapper.selectFuzzy(title);

        return PageInfo.of(list);
    }

    public int deleteBatch(List<Integer> ids) {
        int rows = 0;
        for (Integer id : ids) {
            Article article = articleMapper.selectById(id);
            if (article == null){
                throw new ServiceException(ErrorCode.EMPLOYEE_NOT_FOUND);
            }
            int row =  articleMapper.deleteById(id);
            if(row!=1){
                throw new ServiceException(ErrorCode.EMPLOYEE_DELETE_ERROR);
            }
            rows++;
        }
        return rows;
    }


    /**
     * 用户点赞文章
     * @param articleId 文章ID
     * @param userIdentifier 用户的唯一标识 (e.g., "ROLE-USERNAME")
     */
    public void likeArticle(Integer articleId, String userIdentifier) {
        // 1. 持久化到数据库
        articleLikeMapper.insert(articleId, userIdentifier);
        String key = ARTICLE_LIKES_KEY_PREFIX + articleId;
        // 2. 更新缓存
        // 检查并移除可能存在的空值占位符，这是您提出的关键优化点
        stringRedisTemplate.opsForSet().remove(key, EMPTY_CACHE_PLACEHOLDER);
        stringRedisTemplate.opsForSet().add(key, userIdentifier);
    }

    /**
     * 用户取消点赞文章
     * @param articleId 文章ID
     * @param userIdentifier 用户的唯一标识
     */
    public void unlikeArticle(Integer articleId, String userIdentifier) {
        // 1. 从数据库删除
        articleLikeMapper.delete(articleId, userIdentifier);
        String key = ARTICLE_LIKES_KEY_PREFIX + articleId;
        stringRedisTemplate.opsForSet().remove(key, userIdentifier);
    }

    /**
     * 检查用户是否已点赞某篇文章
     * @param articleId 文章ID
     * @param userIdentifier 用户的唯一标识
     * @return true 如果已点赞, 否则 false
     */
    /**
     * 检查用户是否已点赞 (防穿透最终版)
     */
    public boolean isUserLikedArticle(Integer articleId, String userIdentifier) {
        String key = ARTICLE_LIKES_KEY_PREFIX + articleId;

        // 1. 检查缓存是否存在
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            return Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(key, userIdentifier));
        }

        // 2. 缓存不存在，从数据库加载全量数据
        List<String> userIdentifiersFromDb = articleLikeMapper.findUsersByArticleId(articleId);

        // 3. 同步重建缓存
        rebuildLikeCache(articleId, userIdentifiersFromDb);

        // 4. 从本次从数据库加载的数据中判断
        return userIdentifiersFromDb.contains(userIdentifier);
    }
    /**
     * 同步重建缓存 (最终修正版)
     * @param articleId 文章ID
     * @param userIdentifiers 从数据库加载的用户列表
     */
    private void rebuildLikeCache(Integer articleId, List<String> userIdentifiers) {
        String key = ARTICLE_LIKES_KEY_PREFIX + articleId;

        // --- V 关键修正 V ---
        // 在写入新数据前，先删除旧的键，确保状态干净。
        stringRedisTemplate.delete(key);
        // --- ^ 关键修正 ^ ---

        if (!userIdentifiers.isEmpty()) {
            stringRedisTemplate.opsForSet().add(key, userIdentifiers.toArray(new String[0]));
        } else {
            // 缓存空结果
            stringRedisTemplate.opsForSet().add(key, EMPTY_CACHE_PLACEHOLDER);
        }
        stringRedisTemplate.expire(key, 24, TimeUnit.HOURS);
    }

    /**
     * 获取文章的点赞总数 (依然可以从Redis实时获取)
     */
    /**
     * 获取文章的点赞总数
     */
    public long getArticleLikeCount(Integer articleId) {
        String key = ARTICLE_LIKES_KEY_PREFIX + articleId;
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            // 检查是否为空缓存占位符
            if (Boolean.TRUE.equals(stringRedisTemplate.opsForSet().isMember(key, EMPTY_CACHE_PLACEHOLDER))) {
                return 0;
            }
            Long size = stringRedisTemplate.opsForSet().size(key);
            return size != null ? size : 0;
        }

        // 缓存不存在时，可以从数据库获取（可选，取决于业务对实时性的要求）
        // 这里我们信赖缓存重建机制，暂时返回0
        return 0;
    }




}
